<template>
  <div class="gradeList">
    <el-tabs v-model="activeName" type="card" class="tabs" @tab-click="handleClick">
      <el-tab-pane label="课时管理" name="first">
        <div class="header">
          <el-button type="primary" @click="handleAdd">添加课时信息</el-button>
          <el-dialog title="课时信息" :visible.sync="dialogAddVisible">
            <div class="dialogAdd">
              <FormAdd btnMsg="添加课时" @success="doNext"></FormAdd>
            </div>
          </el-dialog>
          <el-input placeholder="输入关键字搜索" v-model="search" class="input-with-select">
            <el-button slot="append" icon="el-icon-search" @click="findUser"></el-button>
          </el-input>
        </div>
        <el-table :data="periodList" height="520" :fit="true" style="width: 90%x`; padding: 20px; margin: 0 auto">
          <el-table-column prop="lessonDay" label="lessonDay" width="200" show-overflow-tooltip>
          </el-table-column>
          <el-table-column prop="lessonWeek" label="lessonWeek" width="260" show-overflow-tooltip>
          </el-table-column>
          <el-table-column label="操作" width="260">
            <template slot-scope="scope">
              <div style="display: flex; flex-direction: row">
                <el-button size="mini" @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
                <el-button size="mini" type="danger" @click="handleDelete(scope.$index, scope.row)">删除</el-button>
              </div>
            </template>
          </el-table-column>
        </el-table>

        <el-dialog title="年级信息" :visible.sync="dialogFormVisible" :append-to-body="true">
          <el-form :model="editInfo" :rules="rules" ref="editForm">
            <el-form-item label="lessonDay" :label-width="formLabelWidth" prop="lessonDay">
              <el-input v-model="editInfo.lessonDay"></el-input>
            </el-form-item>

            <el-form-item label="lessonWeek" :label-width="formLabelWidth" prop="lessonWeek">
              <el-input v-model="editInfo.lessonWeek"></el-input>
            </el-form-item>
          </el-form>
          <div slot="footer" class="dialog-footer">
            <el-button @click="dialogFormVisible = false">取 消</el-button>
            <el-button type="primary" @click="changeInfo('editForm')">确 定</el-button>
          </div>
        </el-dialog>

        <div class="pages">
          <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="currentPage"
            :page-sizes="[10, 20, 30, 40]" :page-size="pageSize" layout="total, sizes, prev, pager, next, jumper"
            :total="total">
          </el-pagination>
        </div>
      </el-tab-pane>
      <el-tab-pane label="学期管理" name="second">
        <div class="header">
          <el-button type="primary" @click="handleAdd">添加学期信息</el-button>
          <el-dialog title="学期信息" :visible.sync="dialogAddVisible">
            <div class="dialogAdd">
              <FormAdd btnMsg="添加学期" @success="doNext"></FormAdd>
            </div>
          </el-dialog>
          <el-input placeholder="输入关键字搜索" v-model="search" class="input-with-select">
            <el-button slot="append" icon="el-icon-search" @click="findUser"></el-button>
          </el-input>
        </div>
        <el-table :data="semesterList" height="520" style="width: 90%; padding: 20px; margin: 0 auto">
          <el-table-column prop="academicYear" label="academicYear" width="200" show-overflow-tooltip>
          </el-table-column>
          <el-table-column prop="semester_name" label="semester_name" width="260" show-overflow-tooltip>
          </el-table-column>
          <el-table-column label="操作" width="260">
            <template slot-scope="scope">
              <div style="display: flex; flex-direction: row">
                <el-button size="mini" type="danger" @click="handleSemesterDelete(scope.$index, scope.row)">删除</el-button>
              </div>
            </template>
          </el-table-column>
        </el-table>

        <div class="pages">
          <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="currentPage"
            :page-sizes="[10, 20, 30, 40]" :page-size="pageSize" layout="total, sizes, prev, pager, next, jumper"
            :total="total">
          </el-pagination>
        </div>
      </el-tab-pane>
    </el-tabs>
  </div>
</template>
  
<script>
import FormAdd from "../FormAdd.vue";

export default {
  name: "GradePage",
  components: {
    FormAdd,
  },
  data() {
    return {
      msg: "年级管理",
      periodList: [],
      semesterList: [],
      // 分页
      currentPage: 1,
      pageSize: 10,
      total: 0,
      // 搜索
      search: "",
      // 编辑
      editInfo: {},
      semesterInfo: {},
      activeName: "first",
      // 控制课时对话框
      dialogFormVisible: false,
      // 控制学期对话框的Boolean
      dialogSemesterVisible: false,
      dialogAddVisible: false,
      formLabelWidth: "120px",
      type: "lesson",
      rules: {

      },
    };
  },
  methods: {
    // 切换导航栏
    async handleClick(tab, event) {
      console.log(tab, event);
      this.tabIndex = tab.index;
      if (tab.index == "1") {
        await this.getsemesterList();
        this.type = "semester";
      } else if (tab.index == "0") {
        this.type = "lesson";
      }
    },
    // 编辑课时
    handleEdit(index, row) {
      console.log(index, row);
      this.editInfo = { ...row };
      this.dialogFormVisible = true;
    },
    // 编辑学期
    handleSemesterEdit(index, row) {
      this.semesterInfo = { ...row };
      this.dialogSemesterVisible = true;
    },
    //
    changeInfo(form) {
      this.$refs[form].validate((valid) => {
        //表单校验
        if (valid) {
          //valid表示验证是否通过，返回值为布尔类型
          this.dialogFormVisible = false;
          console.log(this.editInfo);
          // let obj = this.editInfo;
          this.$axios
            .post(
              "http://39.105.215.62:8200/lesson/updateLesson",
              this.editInfo
            )
            .then(async (res) => {
              console.log(res);
              if (res.code == 200) {
                await this.getList();
                this.$message({
                  message: res.msg,
                  type: "success",
                });
              } else {
                this.$message.error(res.msg);
              }
            });
        } else {
          console.log("表格不能为空!!");
          return false;
        }
      });
    },
    handleDelete(index, row) {
      console.log(index, row.id);
      // 提示信息
      this.$confirm("此操作将永久删除该数据, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
        center: true,
      }).then(async () => {
        let res = await this.$axios.post(
          `http://39.105.215.62:8200/lesson/deleteLesson?id=${row.id}`
        );
        console.log(res);
        if (res.code == 200) {
          if (this.periodList.length == '1') {
            this.currentPage = this.currentPage - 1;
          }
          await this.getList();
          this.$message({
            type: "success",
            message: res.msg,
          });
          //   if (this.periodList.length == 0 && this.currentPage > 1) {
          //     this.currentPage = this.currentPage - 1;
          //     await this.getList();
          //   }
        }
      });
    },
    handleSemesterDelete(index, row) {
      console.log(index, row.id);
      // 提示信息
      this.$confirm("此操作将永久删除该数据, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
        center: true,
      }).then(async () => {
        let res = await this.$axios.post(
          `http://39.105.215.62:8200/semester/deleteSemester?id=${row.id}`
        );
        console.log(res);
        if (res.code == 200) {
          console.log(this.semesterList.length, "此时输出是长度")
          if (this.semesterList.length == 1) {
            this.currentPage = this.currentPage - 1;
          }
          await this.getsemesterList();
          this.$message({
            type: "success",
            message: res.msg,
          });
          //   if (this.semesterList.length == 0 && this.currentPage > 1) {
          //     this.currentPage = this.currentPage - 1;
          //     console.log(this.currentPage, "此时输出的是page");
          //     await this.getsemesterList();
          //   }
        }
      });
    },
    handleAdd() {
      this.dialogAddVisible = true;
    },
    async doNext(msg) {
      console.log("此时执行了doNext");
      if (msg) {
        this.dialogAddVisible = false;
        console.log(this.index);
        console.log(this.type);
        if (this.type == "semester") {
          console.log("此时执行是");
          await this.getsemesterList();
        } else if (this.type == "lesson") {
          await this.getList();
        }
      }
    },
    async getList() {
      let res = await this.$axios.post(
        `http://39.105.215.62:8200/lesson/selectLesson?pageNum=${this.currentPage}&pageSize=${this.pageSize}&schoolId=${this.schoolId}&gradeId=0`
      );
      console.log(res);
      this.total = res.data.total;
      this.periodList = res.data.records;
    },
    async getsemesterList() {
      let res = await this.$axios.post(
        `http://39.105.215.62:8200/semester/searchSemester?pageSize=${this.pageSize}&pageNum=${this.currentPage}&schoolId=${this.schoolId}`
      );
      console.log(res);
      let infoData = res.data.records.map(item => {
        if (item.semester == '1') {
          item.semester_name = "上学期"
        } else if (item.semester == '2') {
          item.semester_name = "下学期"
        }
        return item;
      })
      infoData.sort((a, b) => {
        if (a.academicYear != b.academicYear) {
          return b.academicYear - a.academicYear;
        } else {
          return a.semester - b.semester
        }
      })

      this.total = res.data.total;
      this.semesterList = infoData;
      console.log(infoData);
    },
    async handleSizeChange(val) {
      console.log(`每页 ${val} 条`);
      this.pageSize = val;
      if (this.type == 'lesson') {
        await this.getList();
      } else if (this.type == 'semester') {
        await this.getsemesterList();
      }
    },
    async handleCurrentChange(val) {
      console.log(`当前页: ${val}`);
      this.currentPage = val;
      if (this.type == 'lesson') {
        await this.getList();
      } else if (this.type == 'semester') {
        await this.getsemesterList();
      }
    },
    async findUser() {
      if (this.search == "") {
        await this.getList();
        this.$message.error("请输入关键字进行查找!");
      } else {
        let result = await this.$axios.post(
          "http://39.105.215.62:8200/grade/findGrades?pageNum=1&pageSize=10",
          { gradeId: "", gradeName: this.search, schoolId: 1 }
        );
        console.log(result);
        this.gradeList = result.data.records;
        this.total = result.data.total;
        if (result.data.total == 0) {
          this.$message.error(result.msg);
        } else {
          this.$message.success(result.msg);
        }
        this.search = "";
      }
    },
  },
  // 生命周期函数--钩子函数一般在初始化页面完成后，再对DOM节点进行相关操作
  async mounted() {
    this.schoolId = JSON.parse(sessionStorage.getItem("info")).schoolId;
    console.log(this.$route.query);
    this.$emit("transfer", this.msg);
    await this.getList();
  },
};
</script>
  
  <!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
.tabs {
  margin-left: 20px;
}

.header {
  display: flex;
  flex-direction: row;
  justify-content: space-around;
  align-items: center;
  border-bottom: 1px solid #ccc;
  padding: 5px;
}

.input-with-select {
  width: 400px;
}

.dialogAdd {
  display: flex;
  justify-content: center;
  align-items: center;
}

.pages {
  margin: 20px auto;
}
</style>
  